package cn.xcyy.itcc.service.impl;

import cn.xcyy.itcc.doc.CourseDoc;
import cn.xcyy.itcc.domain.*;
import cn.xcyy.itcc.dto.CourseDto;
import cn.xcyy.itcc.dto.CourseSendMessageDto;
import cn.xcyy.itcc.enums.GlodalErrorCode;
import cn.xcyy.itcc.feign.CourseEsFeignClien;
import cn.xcyy.itcc.mapper.CourseMapper;
import cn.xcyy.itcc.mapper.CourseTypeMapper;
import cn.xcyy.itcc.result.JSONResult;
import cn.xcyy.itcc.service.*;
import cn.xcyy.itcc.util.AssertUtil;
import cn.xcyy.itcc.vo.CourseDetailShowVo;
import cn.xcyy.itcc.vo.CourseOrderVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-09-30
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private ICourseDetailService courseDetailService;

    @Autowired
    private ICourseMarketService courseMarketService;

    @Autowired
    private ICourseResourceService courseResourceService;

    @Autowired
    private ICourseSummaryService courseSummaryService;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Autowired
    private CourseEsFeignClien courseEsFeignClien;

    @Autowired
    private ICourseChapterService courseChapterService;


    /**
     * 添加
     *
     * @param courseDto
     */
    @Override
    public void save(CourseDto courseDto) {
        Course course = courseDto.getCourse();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        CourseMarket courseMarket = courseDto.getCourseMarket();
        CourseResource courseResource = courseDto.getCourseResource();
        List<Long> teacherIds = courseDto.getTeacherIds();

        Course courseTmp = selectByName(course.getName());
        AssertUtil.isNull(courseTmp, GlodalErrorCode.COURSE_EXISIS_ERROR);

        Long courseId = saveCourse(course, teacherIds);

        courseDetail.setId(courseId);
        saveCourseDetail(courseMarket);

        courseResource.setCourseId(courseId);
        saveCourseResourse(courseResource);

        initCourseSummary(courseId);

        courseMapper.saveCourseTeacher(courseId, teacherIds);
        courseTypeMapper.updateTotalCountById(course.getCourseTypeId());
    }

    /**
     * 课程上架
     *
     * @param id
     */
    @Override
    public void onLineCourse(Long id) {
        Course course = selectById(id);
        //校验课程是否同步
        AssertUtil.isNotNull(course, GlodalErrorCode.COURSE_IS_NULL_ERROR);

        Boolean boo = Course.STATUS_ON == course.getStatus();
        AssertUtil.isFalse(boo, GlodalErrorCode.COURSE_ON_ERROR);
        //修改状态
        course.setStatus(Course.STATUS_ON);
        updateById(course);

        //吧课程添加到Es
        CourseDoc courseDoc = new CourseDoc();

        CourseMarket courseMarket = courseMarketService.selectById(id);
        CourseSummary courseSummary = courseSummaryService.selectById(id);
        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
        //使用beanUtils工具
        BeanUtils.copyProperties(course, courseDoc);
        BeanUtils.copyProperties(course, courseMarket);
        BeanUtils.copyProperties(course, courseSummary);

        courseDoc.setTypeName(courseType.getName());

        courseEsFeignClien.courseEsAdd(courseDoc);

        sendMessage(course.getId());

    }

    @Override
    public CourseDetailShowVo courseDetailShow(Long courseId) {
        AssertUtil.isNotNull(courseId, GlodalErrorCode.SERVICE_PARAM_IS_NULL);
        // 1.查询课程信息
        Course course = selectById(courseId);
        // 1.1.判断当前课程是否已发布，如果没发布报错
        Boolean boo = Course.STATUS_ON == course.getStatus();
        AssertUtil.isTrue(boo, GlodalErrorCode.ILLEGAL_REQUEST_ERROR);

        AssertUtil.isNotNull(course, GlodalErrorCode.NO);
        // 2.查询销售信息
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        // 3.查询详情信息
        CourseDetail courseDetail = courseDetailService.selectById(courseId);
        // 4.查询统计信息
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        // 5.查询老师信息
        List<Teacher> teachers = teacherService.selectByCourseId(courseId);
        // 6.查询课程章节
        Wrapper<CourseChapter> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id", courseId);
        List<CourseChapter> courseChapters = courseChapterService.selectList(wrapper);
        // 7.查询章节对应视频
        List<Long> courseChapterIds = courseChapters.stream().map(CourseChapter::getId).collect(Collectors.toList());
        if (courseChapterIds.size() > 0) {
            JSONResult jsonResult = courseEsFeignClien.searchMediaFiles(courseChapterIds);
            AssertUtil.isTrue(jsonResult.isSuccess(), GlodalErrorCode.SERVICE_ERROR);
            AssertUtil.isNotNull(jsonResult.getData(), GlodalErrorCode.NO);
            List<MediaFile> mediaFilesTmp = JSONObject.parseArray(jsonResult.getData().toString(), MediaFile.class);
            courseChapters.forEach(cc -> {
                ArrayList<MediaFile> mediaFiles = new ArrayList<>();
                mediaFilesTmp.forEach(mf -> {
                    if (cc.getId().equals(mf.getChapterId())) {
                        mediaFiles.add(mf);
                    }
                });
                cc.setMediaFiles(mediaFiles);

            });
        }
        return null;
    }


        @Override
        public CourseOrderVo courseOrderInfo (String courseIds){
            return null;
        }
        private void sendMessage (Long courseId){
            CourseSendMessageDto courseSendMessageDto = new CourseSendMessageDto();
        }
        private void initCourseSummary (Long courseId){
            CourseSummary courseSummary = new CourseSummary();
            courseSummary.setId(courseId);
            courseSummaryService.insert(courseSummary);
        }

        private void saveCourseResourse (CourseResource courseResource){
            courseResourceService.insert(courseResource);
        }

        private void saveCourseDetail (CourseMarket courseMarket){
            courseMarketService.insert(courseMarket);
        }
        private Long saveCourse (Course course, List < Long > teacherIds){
            course.setStatus(Course.STATUS_OFF);
            course.setLoginId(3L);
            course.setLoginUserName("133330964748");
            String teacherNames = selectBatchIds(teacherIds)
                    .stream().map(teacher -> teacher.getName()).collect(Collectors.joining(","));
            course.setTeacherNames(teacherNames);
            insert(course);
            return course.getId();
        }
        private Course selectByName (String name){
            Wrapper<Course> wrapper = new EntityWrapper<>();
            wrapper.eq("name", name);
            return selectOne(wrapper);
        }
}
